package com.bjc.scheduler.elasticjob.springboot.job;

import com.bjc.scheduler.elasticjob.springboot.model.FileCustom;
import com.bjc.scheduler.elasticjob.springboot.service.FileService;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: elastic-job-springboot
 * @description:
 * @author: bjc
 * @create: 2021-08-15 22:00
 */
@Component
public class FileBackupJobDb implements SimpleJob {

    /**
     * 每次任务执行要备份的文件的数量
     */
    private final int FETCH_SIZE = 1;

    @Autowired
    private FileService fileService;

    /**
     * 任务执行代码逻辑
     * @param shardingContext
     */
    @Override
    public void execute(ShardingContext shardingContext) {
        System.out.println("作业分片:" + shardingContext.getShardingItem());

        //分片参数0=text,1=image,2=radio,3=video 参数就是text,image,radio,video
        String jobParameter = shardingContext.getShardingParameter();

        //获取为备份的文件
        List<FileCustom> fileCustomList = fetchUnBackupFiles(jobParameter,FETCH_SIZE);

        //进行文件备份
        backupFiles(fileCustomList);
    }

    /**
     * 获取未备份的文件
     * @param count  文件数量
     * @return
     */
    public List<FileCustom> fetchUnBackupFiles(String fileType,int count){
        List<FileCustom> fileCustoms = fileService.fetchUnBackupFiles(fileType, count);
//        System.out.printf("time:%s,获取文件%d个\n", LocalDateTime.now(),num);
        return fileCustoms;
    }

    /**
     * 文件备份
     * @param files  要备份的文件
     */
    public void backupFiles(List<FileCustom> files){
        fileService.backupFiles(files);
    }
}
